package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"io"
	"log"
	"net/http"
)

func getJSON(sqlString string) (string, error) {
	db, err := sql.Open("mysql", "root:linux2016@/linux")
	if err != nil {
    panic(err.Error())  // Just for example purpose. You should use proper error handling instead of panic
  }
  defer db.Close()
  rows, err := db.Query(sqlString)
  if err != nil {
      return "", err
  }
  defer rows.Close()
  columns, err := rows.Columns()
  if err != nil {
      return "", err
  }
  count := len(columns)
	tableData := make([]map[string]interface{}, 0)
  resultData := make(map[string]interface{}, 0)
  values := make([]interface{}, count)
  valuePtrs := make([]interface{}, count)
  for rows.Next() {
      for i := 0; i < count; i++ {
          valuePtrs[i] = &values[i]
      }
      rows.Scan(valuePtrs...)
      entry := make(map[string]interface{})
      for i, col := range columns {
          var v interface{}
          val := values[i]
          b, ok := val.([]byte)
          if ok {
              v = string(b)
          } else {
              v = val
          }
          entry[col] = v
      }
      tableData = append(tableData, entry)
  }
	resultData["from"] = "golang"
	resultData["list"] = tableData
  jsonData, err := json.Marshal(resultData)
  if err != nil {
      return "", err
  }
  return string(jsonData), nil
}

func getList(w http.ResponseWriter, r *http.Request) {
	result, err := getJSON("SELECT * from mock")
	if err != nil {
			fmt.Println(err)
	}
	io.WriteString(w, result)
}

func main() {
	http.HandleFunc("/mysql", getList)
	err := http.ListenAndServe(":3002", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}
